//
//  XLFormRowDescriptor.m
//  XLForm ( https://github.com/xmartlabs/XLForm )
//
//  Copyright (c) 2015 Xmartlabs ( http://xmartlabs.com )
//
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.

#import "XLForm.h"
#import "List.h"
#import "Row.h"


@interface Row ()
@property (nullable) id cellClass;
@property UITableViewCellStyle cellStyle;
@end

@implementation Row

-(instancetype)init
{
    self = [super init];
    if (self){
        _cellStyle = UITableViewCellStyleValue1;
        _height = -2;
        [self addObserver:self forKeyPath:@"cellModel" options:NSKeyValueObservingOptionOld | NSKeyValueObservingOptionNew context:0];
    }
    return self;
}

+(nonnull instancetype)row:(void (^_Nullable)(Row * _Nonnull row))rowConfig
{
    Row *result = [[Row alloc] init];
    BlockGoGo(rowConfig, result);
    return result;
}

-(void)select
{
    if (self.section && self.section.form && self.section.form.list)
    {
        Form *form = self.section.form;
        List *list = self.section.form.list;
        
        NSIndexPath *indexPath = [form indexPathOfRow:self];
        
        if (indexPath){
            [list.tableView selectRowAtIndexPath:indexPath animated:YES scrollPosition:(UITableViewScrollPositionNone)];
        }
    }
}


/*
     cell被点选时：
     1. 完成UI响应和Cell内部变化
     2. 向上回调Row的动态配置，完成逻辑处理
 */
-(void)didSelected
{
    if ([self.cell respondsToSelector:@selector(didSelected)]){
        [self.cell didSelected];
    }
    
    if ([self respondsToSelector:@selector(didSelectedBlock)])
    {
        [self didSelectedSelector];
    }
    else if (self.didSelectedBlock)
    {
        BlockGoGo(self.didSelectedBlock, self);
    }
}

-(void)deselect
{
    if (self.section && self.section.form && self.section.form.list)
    {
        Form *form = self.section.form;
        List *list = self.section.form.list;
        
        NSIndexPath *indexPath = [form indexPathOfRow:self];
        
        if (indexPath){
            [list.tableView deselectRowAtIndexPath:indexPath animated:YES];
        }
    }
}

-(void)reload
{
    if (self.section && self.section.form && self.section.form.list)
    {
        Form *form = self.section.form;
        List *list = self.section.form.list;
        
        NSIndexPath *indexPath = [form indexPathOfRow:self];
        if (indexPath){
            [list.tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationNone];
        }
    }
}

-(void)update
{
    Cell * cell = self.cell;
    [cell onModelChanged];
    [cell setNeedsUpdateConstraints];
    [cell setNeedsLayout];
}

-(NSString *)description
{
    return self.tag;
}

// In the implementation
-(id)copyWithZone:(NSZone *)zone
{
    Row * row = [Row new];
    row.rowType = [self.rowType copy];
    row.cellClass = [self.cellClass copy];
    if (self.didSelectedBlock){
        row.didSelectedBlock = [self.didSelectedBlock copy];
    }
    else if (self.didSelectedSelector){
        row.didSelectedSelector = self.didSelectedSelector;
    }
    return row;
}

-(void)dealloc
{
    @try {
        [self removeObserver:self forKeyPath:@"cellModel"];
    }
    @catch (NSException * __unused exception) {}
}

#pragma mark - KVO

/**
 监控Model变化，当Model发生变化时：
 1. 通知Cell，重新计算告诉
 2. 通知Cell，重新调整布局和绑定
 3. 通知List，关联相关操作
 */
-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
    if (!self.section) return;
    if (object == self && [keyPath isEqualToString:@"cellModel"]){
        if ([[change objectForKey:NSKeyValueChangeKindKey] isEqualToNumber:@(NSKeyValueChangeSetting)]){
            id newValue = [change objectForKey:NSKeyValueChangeNewKey];
            id oldValue = [change objectForKey:NSKeyValueChangeOldKey];
            
            if ([[self.cell class] respondsToSelector:@selector(heightForRow:)]){
                self.height = [[self.cell class] heightForRow:self];
            }
            
            if ([self.cell performSelector:@selector(onModelChanged)]){
                [self.cell onModelChanged];
            }
            
            if (self.onModelChanged) {
                self.onModelChanged(oldValue, newValue, self);
            }
        }
    }
}


#pragma mark - lazy load
-(Cell *)cell
{
    if (!_cell)
    {
        id cellClass = self.cellClass ?: [self.section.form.list cellClassesForRowTypes][self.rowType];
        _cell = [[cellClass alloc] initWithStyle:self.cellStyle reuseIdentifier:nil];
        _cell.row = self;
    }
    return _cell;
}

-(void)setDidSelectedSelector:(SEL)didSelectedSelector
{
    _didSelectedBlock = nil;
    _didSelectedSelector = didSelectedSelector;
}

-(void)setDidSelectedBlock:(void (^)(Row *))didSelectedBlock
{
    _didSelectedSelector = nil;
    _didSelectedBlock = didSelectedBlock;
}
@end
